//
//  PhotoListViewController.m
//  SecretAlbums
//
//  Created by BabyFinancial on 15/6/12.
//  Copyright (c) 2015年 BabyFinancial. All rights reserved.
//

#import "ThumbnailListViewController.h"
#import "SecretAlbumsConst.h"
#import "SecretAlbumsLogic.h"
#import "CTAssetsPickerController.h"
#import "ThumbnailCell.h"
#import "CTAssetsPickerCommon.h"
#import "MBProgressHUD.h"
#import "SupplementaryView.h"
#import "AssetPageViewController.h"
#import "Masonry.h"
#import "ThumbnailListNavigationController.h"
#import <AVFoundation/AVFoundation.h>
#import "AppDelegate.h"

@interface ThumbnailListViewController () <CTAssetsPickerControllerDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIBarButtonItem *selectItem;
@property (nonatomic, strong) UIBarButtonItem *cancelItem;
@property (nonatomic, strong) UIBarButtonItem *addItem;
@property (nonatomic, assign) BOOL isOpenSelect;
@property (nonatomic, strong) NSArray *medias;
@property (nonatomic, strong) UILabel *noThumbnailLabel;
@property (nonatomic, strong) NSMutableArray *selectMedias;

@property (nonatomic, strong) UIBarButtonItem *actionItem;
@property (nonatomic, strong) UILabel *selectLabel;
@property (nonatomic, strong) UIBarButtonItem *trashItem;

@end

@implementation ThumbnailListViewController

static NSString * const ThumbnailCellIdentifier = @"ThumbnailCellIdentifier";
NSString * const SupplementaryViewIdentifier = @"SupplementaryViewIdentifier";

- (instancetype)init
{
    if (self = [super initWithCollectionViewLayout:[self collectionViewFlowLayoutOfOrientation]]) {
        ;
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"Album", nil);
    
    [self.collectionView registerClass:[ThumbnailCell class] forCellWithReuseIdentifier:ThumbnailCellIdentifier];
    [self.collectionView registerClass:SupplementaryView.class
            forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                   withReuseIdentifier:SupplementaryViewIdentifier];
    
    self.collectionView.backgroundColor = SABackgroundColor;
    self.navigationController.view.tintColor = SATintColor;
    self.clearsSelectionOnViewWillAppear = YES;
    self.collectionView.allowsMultipleSelection = YES;
    
    [self setupNavigationItem];
    [self setupToolBar];
    self.isOpenSelect = NO;
    
    self.medias = [SecretAlbumsLogic mediaArrayWithCurrentAlbumID];
    self.selectMedias = [NSMutableArray new];
    [self setupShowNoThumbnailLabel];
    
    // 添加长按手势，长按item也能进入page页面
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(presentPageViewControllerOnLongPress:)];
    [self.collectionView addGestureRecognizer:longPress];
}

- (UILabel *)noThumbnailLabel
{
    if (!_noThumbnailLabel) {
        _noThumbnailLabel = [UILabel new];
        _noThumbnailLabel.textColor = [UIColor lightGrayColor];
        _noThumbnailLabel.font = [UIFont systemFontOfSize:Adapter_X(24.0f)];
        _noThumbnailLabel.textAlignment = NSTextAlignmentCenter;
        _noThumbnailLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [self.collectionView addSubview:_noThumbnailLabel];
        
        [_noThumbnailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.collectionView.mas_centerX);
            make.centerY.equalTo(self.collectionView.mas_centerY).offset(Adapter_Y(-100));
        }];
    }
    
    return _noThumbnailLabel;
}

- (void)setIsOpenSelect:(BOOL)isOpenSelect
{
    _isOpenSelect = isOpenSelect;
    
    if (!isOpenSelect) {
        [self.selectMedias removeAllObjects];
        self.selectLabel.text = NSLocalizedString(@"Select Items", nil);
        [self.actionItem setEnabled:NO];
        [self.trashItem setEnabled:NO];
    }
    
    self.navigationItem.rightBarButtonItems = @[self.addItem, _isOpenSelect ? self.cancelItem : self.selectItem];
    [self.navigationController setToolbarHidden:!_isOpenSelect animated:YES];
    
    [self.collectionView reloadData];
}

#pragma mark - 私有方法

- (void)presentPageViewControllerOnLongPress:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        CGPoint point           = [longPress locationInView:self.collectionView];
        NSIndexPath *indexPath  = [self.collectionView indexPathForItemAtPoint:point];
        
        if (indexPath) {
            self.isOpenSelect = NO;
            AssetPageViewController *pageController = [[AssetPageViewController alloc] initWithMedias:self.medias];
            pageController.pageIndex = indexPath.row;
            pageController.transitioningDelegate = (ThumbnailListNavigationController *)self.navigationController;
            
            [self presentViewController:pageController animated:YES completion:nil];
        }
    }
}

- (void)setupNavigationItem
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Logout"] style:UIBarButtonItemStylePlain target:self action:@selector(backBarItemOnclik:)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.selectItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Select", nil) style:UIBarButtonItemStylePlain target:self action:@selector(selectItemOnclik:)];
    self.cancelItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Cancel", nil) style:UIBarButtonItemStyleDone target:self action:@selector(cancelItemOnclik:)];
    self.addItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Add"] style:UIBarButtonItemStylePlain target:self action:@selector(addItemOnclik:)];
}

- (void)setupToolBar
{
    self.actionItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionItemOnclick:)];
    
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    self.selectLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
    self.selectLabel.text = NSLocalizedString(@"Select Items", nil);
    self.selectLabel.textAlignment = NSTextAlignmentCenter;
    self.selectLabel.textColor = [UIColor whiteColor];
    UIBarButtonItem *titleItem = [[UIBarButtonItem alloc] initWithCustomView:self.selectLabel];
    
    self.trashItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(trashItemOnclick:)];
    
    self.toolbarItems = @[self.actionItem, spaceItem, titleItem, spaceItem, self.trashItem];
}

- (void)backBarItemOnclik:(UIBarButtonItem *)barButtonItem
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate logoutWithAnimation:YES];
}

- (void)selectItemOnclik:(UIBarButtonItem *)barButtonItem
{
    self.isOpenSelect = YES;
}

- (void)cancelItemOnclik:(UIBarButtonItem *)barButtonItem
{
    self.isOpenSelect = NO;
}

- (void)addItemOnclik:(UIBarButtonItem *)barButtonItem
{
    self.isOpenSelect = NO;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                             cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                                             destructiveButtonTitle:nil
                                                             otherButtonTitles:NSLocalizedString(@"TakePhoto", nil),
                                                                               NSLocalizedString(@"ChoosePhoto", nil),
                                  nil];
    [actionSheet showInView:self.navigationController.view];
}

- (void)actionItemOnclick:(UIBarButtonItem *)barButtonItem
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                               destructiveButtonTitle:NSLocalizedString(@"Save to system album", nil)
                                                    otherButtonTitles:nil];
    actionSheet.tag = 100;
    [actionSheet showInView:self.navigationController.view];
}

- (void)trashItemOnclick:(UIBarButtonItem *)barButtonItem
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                               destructiveButtonTitle:[NSString stringWithFormat:NSLocalizedString(@"Delete %ld Items", nil), self.selectMedias.count]
                                                    otherButtonTitles:nil];
    actionSheet.tag = 101;
    [actionSheet showInView:self.navigationController.view];
}

- (void)setupShowNoThumbnailLabel
{
    if (self.medias.count <= 0) {
        self.noThumbnailLabel.text = NSLocalizedString(@"NoPhotosOrVideos", nil);
    } else {
        self.noThumbnailLabel.text = @"";
    }
}

- (void)openCamera
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Error", nil)
                                                              message:NSLocalizedString(@"Device has no camera", nil)
                                                             delegate:nil
                                                    cancelButtonTitle:NSLocalizedString(@"Close", nil)
                                                    otherButtonTitles: nil];
        [alertView show];
        
        return;
    }
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == ALAuthorizationStatusRestricted || authStatus == ALAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:NSLocalizedString(@"This app does not have access to your camera", nil)
                                  message:NSLocalizedString(@"You can enable access in Privacy Settings", nil)
                                  delegate:nil
                                  cancelButtonTitle:NSLocalizedString(@"Close", nil)
                                  otherButtonTitles:nil];
        [alertView show];
    }
    
    UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
    
    cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
    cameraUI.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    [cameraUI setVideoQuality:UIImagePickerControllerQualityTypeHigh];
    cameraUI.allowsEditing = NO;
    cameraUI.delegate = self;
    
    [self presentViewController:cameraUI animated:YES completion:nil];
}

#pragma mark - <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.medias.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ThumbnailCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ThumbnailCellIdentifier forIndexPath:indexPath];
    
    [cell bind:self.medias[indexPath.row]];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    SupplementaryView *view =
    [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter
                                       withReuseIdentifier:SupplementaryViewIdentifier
                                              forIndexPath:indexPath];
    view.tag = 999;
    [view bind:self.medias];
    
    view.hidden = (self.medias.count == 0);
    
    return view;
}

#pragma mark <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.isOpenSelect) {
        [collectionView deselectItemAtIndexPath:indexPath animated:NO];
        
        AssetPageViewController *pageController = [[AssetPageViewController alloc] initWithMedias:self.medias];
        pageController.pageIndex = indexPath.row;
        pageController.transitioningDelegate = (ThumbnailListNavigationController *)self.navigationController;
        
        [self presentViewController:pageController animated:YES completion:nil];
    } else {
        [self.selectMedias addObject:self.medias[indexPath.row]];
        
        if (0 == self.selectMedias.count) {
            self.selectLabel.text = NSLocalizedString(@"Select Items", nil);
            [self.actionItem setEnabled:NO];
            [self.trashItem setEnabled:NO];
        } else {
            self.selectLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%ld Items Selected", nil), self.selectMedias.count];
            [self.actionItem setEnabled:YES];
            [self.trashItem setEnabled:YES];
        }
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isOpenSelect) {
        [self.selectMedias removeObject:self.medias[indexPath.row]];
        
        if (0 == self.selectMedias.count) {
            self.selectLabel.text = NSLocalizedString(@"Select Items", nil);
            [self.actionItem setEnabled:NO];
            [self.trashItem setEnabled:NO];
        } else {
            self.selectLabel.text = [NSString stringWithFormat:NSLocalizedString(@"%ld Items Selected", nil), self.selectMedias.count];
            [self.actionItem setEnabled:YES];
            [self.trashItem setEnabled:YES];
        }
    }
}

#pragma mark - CTAssetsPickerControllerDelegate

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    MBProgressHUD *hun = [MBProgressHUD showHUDAddedTo:picker.view animated:YES];
    [SecretAlbumsLogic addAssets:assets completion:^{
        [hun hide:YES];
        [self dismissViewControllerAnimated:YES completion:nil];

        NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:[SecretAlbumsLogic mediaArrayWithCurrentAlbumID]];
        NSMutableArray *indexPathArray = [NSMutableArray new];
        
        for (int i=0; i<mutableArray.count-self.medias.count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.medias.count+i inSection:0];
            [indexPathArray addObject:indexPath];
        }
        self.medias = mutableArray;
        [self setupShowNoThumbnailLabel];
        SupplementaryView *footer = (SupplementaryView *)[self.collectionView viewWithTag:999];
        [footer bind:self.medias];
        footer.hidden = (self.medias.count == 0);
        [self.collectionView insertItemsAtIndexPaths:indexPathArray];
        [self.collectionView scrollToItemAtIndexPath:indexPathArray.lastObject atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
    }];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    MBProgressHUD *hun = [MBProgressHUD showHUDAddedTo:picker.view animated:YES];
    [SecretAlbumsLogic addMedia:info completion:^{
        [hun hide:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
        
        NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:[SecretAlbumsLogic mediaArrayWithCurrentAlbumID]];
        NSMutableArray *indexPathArray = [NSMutableArray new];
        
        for (int i=0; i<mutableArray.count-self.medias.count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.medias.count+i inSection:0];
            [indexPathArray addObject:indexPath];
        }
        self.medias = mutableArray;
        [self setupShowNoThumbnailLabel];
        SupplementaryView *footer = (SupplementaryView *)[self.collectionView viewWithTag:999];
        [footer bind:self.medias];
        footer.hidden = (self.medias.count == 0);
        [self.collectionView insertItemsAtIndexPaths:indexPathArray];
        [self.collectionView scrollToItemAtIndexPath:indexPathArray.lastObject atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
    }];
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (100 == actionSheet.tag) {
        // 保存至系统相册
        if (0 == buttonIndex) {
            MBProgressHUD *hun = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            [SecretAlbumsLogic addMediaToSystemAlbum:self.selectMedias completion:^{
                hun.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Checkmark.png"]];
                hun.mode = MBProgressHUDModeCustomView;
                hun.labelText = NSLocalizedString(@"Save success", nil);
                [hun hide:YES afterDelay:1];
                
                [self.selectMedias removeAllObjects];
                self.selectLabel.text = NSLocalizedString(@"Select Items", nil);
                [self.actionItem setEnabled:NO];
                [self.trashItem setEnabled:NO];
                [self.collectionView reloadData];
            }];
        }
    } else if (101 == actionSheet.tag) {
        // 删除照片
        if (0 == buttonIndex) {
            NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:self.medias];
            NSMutableArray *indexPathArray = [NSMutableArray new];
            
            for (Media *media in self.selectMedias) {
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[self.medias indexOfObject:media] inSection:0];
                [indexPathArray addObject:indexPath];
                
                [mutableArray removeObject:media];
            }
            self.medias = mutableArray;
            [self setupShowNoThumbnailLabel];
            SupplementaryView *footer = (SupplementaryView *)[self.collectionView viewWithTag:999];
            [footer bind:self.medias];
            footer.hidden = (self.medias.count == 0);
            [self.collectionView deleteItemsAtIndexPaths:indexPathArray];
            
            // 删除本地文件和数据库数据
            [SecretAlbumsLogic delMedias:self.selectMedias];
            
            [self.selectMedias removeAllObjects];
            self.selectLabel.text = NSLocalizedString(@"Select Items", nil);
            [self.actionItem setEnabled:NO];
            [self.trashItem setEnabled:NO];
            [self.collectionView reloadData];
        }
    } else {
        // 添加照片
        if (0 == buttonIndex) {
            // 拍照
            [self openCamera];
        } else if (1 == buttonIndex) {
            // 选取照片
            CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
            picker.delegate = self;
            [self presentViewController:picker animated:YES completion:nil];
        }
    }
}

#pragma mark - Collection View Layout

- (UICollectionViewFlowLayout *)collectionViewFlowLayoutOfOrientation
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    layout.itemSize             = CTAssetThumbnailSize;
    layout.footerReferenceSize  = CGSizeMake(0, 47.0);
    layout.sectionInset            = UIEdgeInsetsMake(9.0, 0, 0, 0);
    layout.minimumInteritemSpacing = (CTIPhone6Plus) ? 0.5 : ( (CTIPhone6) ? 1.0 : 2.0 );
    layout.minimumLineSpacing      = (CTIPhone6Plus) ? 0.5 : ( (CTIPhone6) ? 1.0 : 2.0 );
    
    return layout;
}

@end
